package interface_layer;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import database_layer.*;

/**
 * This servlet handles the logging in of the users in the web service
 */
public class Login extends HttpServlet 
{
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Login()
    {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) 
	{
		try
		{
			String username = request.getParameter("loginusername");
			String password = request.getParameter("loginpassword");
			processing_layer.User loggingInUser = null; 
			if ( null == username || null == password || "" == username || "" == password ) 
			{
					request.getSession().setAttribute("Error","Please fill all fields.");
					response.sendRedirect("index.jsp");
			}
			loggingInUser  = QueryDispatcher.getUserDetails(username);
			if (null == loggingInUser)
			{ 
				// Cant Login now
				request.getSession().setAttribute("Error","Can't register now, Try again later.");
				response.sendRedirect("index.jsp");
				return;
			}
			
			// The user doesn't exist
			else if ( null == loggingInUser.username )
			{
				request.getSession().setAttribute("Error", "No such user.");
			}
			else if ( !password.equals(loggingInUser.password) )
			{
				request.getSession().setAttribute("Error", "User name and Password don't match.");
			}
			else
			{
				if ( database_layer.Common.NO_ERROR != processing_layer.SessionTracker.addConnectedUser(username) )
				{
					request.getSession().setAttribute("Error","The user is already logged in!");
					response.sendRedirect("index.jsp");
					return;
				}
				request.getSession().setAttribute("username", username);
				request.getSession().setAttribute("userType", loggingInUser.isAdmin ? Common.adminType : Common.studentType);
			}
			response.sendRedirect("index.jsp");
		}
		catch (Exception e)
		{
			System.out.println("Exception is : " + e.getLocalizedMessage());
			ErrorHandler.parseForErrors(Common.INTERNAL_ERROR, response, null);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) 
	{
		doGet(request,response);
	}

}
